<?php

namespace app\service;

use app\common\BaseService;
use app\model\Category as CategoryModel;
use think\facade\Db;

class CategoryService extends BaseService
{
  public static function getInstance(): CategoryService
  {
    return parent::getInstance();
  }

  public static function getModel(): CategoryModel
  {
    return CategoryModel::getInstance();
  }

  /*
   * 根据condition获取商品
   */
  public function getCategoryByCondition($conditions = [], $order = ['id' => 'asc']) {
    $conditions[] = ['status', 1, '='];
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  public static function createCategory($name, $data)
  {
    $insertTime = date('Y-m-d H:i:s');
    $insert = [];
    foreach ($data as $value) {
      $insert[] = [
        'category_name' => $name,
        'base' => $value,
        'status' => 1,
        'insert_time' => $insertTime,
        'last_update_time' => $insertTime
      ];
    }
    $res = self::getModel()->insertAll($insert);
    if ($res === false) {
      return ['status' => false, 'msg' => '新增分类失败'];
    }
    return ['status' => true, 'msg' => 'ok'];
  }
}